require(["config"],function(){
	require(["jquery", "template", "header", "zoom", "fly", "carousel", "cookie"], function($, template) {
		function List(){
			this.renderList();
		}
		List.prototype={
			constructor:List,
			//渲染数据
			renderList:function(){
				$.ajax("http://rap2api.taobao.org/app/mock/87266/api/list")
				.done((data)=>{
					//待渲染数据
					var data = {list:data.res_body.list};
					//渲染
					var html = template("list_template",data);
					$("#cakeList").html(html);
					this.addListener();
				})
			},
			
			addListener:function(){
				$(".content").on("click","a",$.proxy(this.clickTitle,this))
				$(".join-basket").click(this.addToCartHandler);
				$(".qrcode-close").click(this.closeCart);
			},
			clickTitle:function(event){
				var kinds= event.target;
				console.log(kinds);
				var child =$(kinds).siblings();
				console.log(child);
				$(child).removeClass("active");
				$(kinds).addClass("active");
				this.renderList();
				
			},
			closeCart:function(){
				$(".qrcode-sw").attr("style","display:none;")
			},
			addToCartHandler: function(event) {
							console.log("111")
			
							// 获取当前选购商品的信息
							var currentProduct = {
								id: $(".prod_id").html(),
								cn: $(".cn").html(),
								en:$(".en").html(),
								img: $(".loaded").attr("src"),
								price: 198,
								amount: 1
							};
							console.log(currentProduct);
							/* 判断是否已选购过当前商品 */
							// 从 cookie 中读取以有的购物车数据
										$.cookie.json = true; // 配置自动在JS值与JSON文本之间相互转换
										var products = $.cookie("cart") || [];
										// 判断是否已有选购
										var has = products.some(function(prod) {
											if (prod.id == currentProduct.id) { // 已有选购商品
												prod.amount++; // 数量自增
												return true;
											}
											return false;
										});
										if (!has) // 未选购
											products.push(currentProduct);
						
										// 保存购物车：存回cookie
										// 数据结构：[{id,title,img,price,amout},{id,title,img,price,amout},{id,title,img,price,amout}]
										$.cookie("cart", products, {
											expires: 10,
											path: "/"
										});
										console.log($(".popup-info").html("您所选的商品已加入购物篮！"));
										$("#maskPopup").attr("style","display:block;")
										$(".popups").attr("style","display:block;")
										$(".btn-cancel").on("click",function(){
											$("#maskPopup").attr("style","display:none;")
										})
										$(".btn-sure").on("click",function(){
											$(".btn-sure").attr("href","/html/cart.html")
										})
										
						}
		}
		new List();
		
	})
});